/*** 
 * @Date: 2020-07-10 09:55:38
 * @LastEditors: leehave
 * @LastEditTime: 2020-09-14 17:06:17
 */
import { loginByCode, authSubscribe, getUserInfo } from '@/service/user'
import {
  saveToken,
  saveLoginStatus,
  saveUserInfo,
  removeToken,
  removeUserInfo,
  removeLoginStatus,
  loadLoginStatus,
  loadToken,
  loadUserInfo,
  removeLoginCode,
  saveLoginCode,
  loadLoginCode
} from '@/utils/cache'
import Router from '@/router'
import { Toast } from 'vant'

const user = {
  namespaced: true,
  state: {
    loginStatus: loadLoginStatus(), // 登录状态
    token: loadToken(), // token
    userInfo: loadUserInfo() || null, // 用户登录信息
    code: loadLoginCode(), //code
    subscribe: null,
    addressHuli: {},
    memberInfo: {}
  },

  mutations: {
    SET_MEMBER_INFO: (state, info) => {
      state.memberInfo = info
    },
    SET_HULI_ADDRESS: (state, payment) => {
      state.addressHuli = payment
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_LOGIN_STATUS: (state, loginStatus) => {
      state.loginStatus = loginStatus
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_CODE: (state, code) => {
      state.code = code
      saveLoginCode(code)
    },
    SET_SUBCRIBE: (state, subscribe) => {
      state.subscribe = subscribe
    }
  }
  ,
  actions: {
    // 登录相关，通过code获取token和用户信息，用户根据自己的需求对接后台
    loginWechatAuth({ dispatch,commit }, code) {
      let params = { code: code }
      return new Promise((resolve, reject) => {
        loginByCode(params)
          .then(res => {
            if (res.status == '200') {
              commit('SET_TOKEN', saveToken(res.data.token))
              commit('SET_LOGIN_STATUS', saveLoginStatus(2))

              // params.openId = res.data.openId
              // authSubscribe(params).then(ressub => {
              //   console.log(ressub,'authSubscribe')
              //   if(ressub.respCode === 'USER_AUTH_001'){
              //     Router.replace({
              //       path: '/user/sub-qcode',
              //       query: {
              //         qrCode: ressub.data
              //       }
              //     })
              //   }else{
              //     getUserInfo({openId: res.data.openId}).then(result => {
              //       if(result.status == '200'){
              //         saveUserInfo(result.data)
              //         commit('SET_USERINFO', result.data)

              //         if(result.data.hasOwnProperty('phone') && result.data.phone == null || result.data.phone == undefined || result.data.phone == ''){
              //           Router.replace({
              //             path: '/user/bind-phone'
              //           })
              //         }else{
              //           Router.replace({
              //             path: '/home/index'
              //           })
              //         }
              //       }else{
              //         Toast('异常？')
              //       }
              //     })
              //   }
              // })
              getUserInfo().then(result => {
                if (result.status == 200) {
                  saveUserInfo(result.data)
                  commit('SET_USERINFO', result.data)
                  if (result.data.hasOwnProperty('tel') && result.data.tel == null || result.data.tel == undefined || result.data.tel == '') {
                    Router.replace({
                      path: '/user/bind-phone'
                    })
                  } else {
                    Router.replace({
                      path: '/home/index'
                    })
                  }
                }else{
                  removeToken()
                  removeUserInfo()
                  removeLoginStatus()
                  removeLoginCode()
                  commit('SET_LOGIN_STATUS', saveLoginStatus(0))
                }
              }).catch(error => Toast(error))
            }
          })
      })
    },
    // 判断是否关注公众号
    AuthSubscribe({ commit }, params) {
      authSubscribe(params).then(res => {
        if (res.status === 'USER_AUTH_001') {
          Router.replace({
            path: '/user/sub-qcode',
            query: {
              qrCode: res.data
            }
          })
        }
      })
    },
    // 设置状态
    setLoginStatus({ commit }, query) {
      console.log(query, 'setLoginStatus')
      if (query === 0 || query === 1) {
        // 上线打开注释，本地调试注释掉，保持信息最新
        removeToken()
        removeUserInfo()
      }
      // 设置不同的登录状态
      commit('SET_LOGIN_STATUS', saveLoginStatus(query))
    },
    // 登出
    fedLogOut({commit}) {
      // 删除token，用户信息，登陆状态
      removeToken()
      removeUserInfo()
      removeLoginStatus()
      removeLoginCode()
      commit('SET_LOGIN_STATUS', saveLoginStatus(0))
      Router.replace({
        path: '/'
      })
      window.location.reload()
    },

    /**
     * vuex用户信息更新
     */
    updateUserInfo({ commit }) {
      getUserInfo().then(result => {
        if (result.data.tel == '' || result.data.hasOwnProperty('tel') && result.data.tel == undefined) {
          Router.replace({
            path: '/user/bind-phone'
          })
        }
        saveUserInfo(result.data)
        console.log(result.data)
        commit('SET_USERINFO', result.data)
      })
    }
  }
}

export default user;
